package com.zheng.log;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Enumeration;

public class LogInterceptor implements HandlerInterceptor {
    private final LogProperties logProperties;
    private final DateTimeFormatter formatter;

    public LogInterceptor(LogProperties logProperties) {
        this.logProperties = logProperties;
        this.formatter = DateTimeFormatter.ofPattern(logProperties.getLogFormat());
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("自定义Starter输出");
        // 如果功能未启用，直接放行
        if (!logProperties.isEnabled()) {
            return true;
        }

        // 检查是否是需要忽略的路径
        String requestPath = request.getRequestURI();
        if (Arrays.asList(logProperties.getIgnorePaths()).contains(requestPath)) {
            return true;
        }

        // 记录请求开始时间
        request.setAttribute("startTime", System.currentTimeMillis());

        // 记录请求信息
        StringBuilder logMsg = new StringBuilder();
        logMsg.append("[")
                .append(LocalDateTime.now().format(formatter))
                .append("] ")
                .append("Request: ")
                .append(request.getMethod())
                .append(" ")
                .append(requestPath);

        // 记录请求参数
        if (logProperties.isLogRequestParams()) {
            logMsg.append(" | Params: {");
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                logMsg.append(paramName)
                        .append("=")
                        .append(request.getParameter(paramName));
                if (paramNames.hasMoreElements()) {
                    logMsg.append(", ");
                }
            }
            logMsg.append("}");
        }

        System.out.println(logMsg.toString());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {
        // 如果功能未启用，直接返回
        if (!logProperties.isEnabled()) {
            return;
        }

        // 检查是否是需要忽略的路径
        String requestPath = request.getRequestURI();
        if (Arrays.asList(logProperties.getIgnorePaths()).contains(requestPath)) {
            return;
        }

        // 计算请求处理时间
        Long startTime = (Long) request.getAttribute("startTime");
        if (startTime != null) {
            long duration = System.currentTimeMillis() - startTime;

            // 记录响应信息
            StringBuilder logMsg = new StringBuilder();
            logMsg.append("[")
                    .append(LocalDateTime.now().format(formatter))
                    .append("] ")
                    .append("Response: ")
                    .append(request.getMethod())
                    .append(" ")
                    .append(requestPath)
                    .append(" | Status: ")
                    .append(response.getStatus())
                    .append(" | Duration: ")
                    .append(duration)
                    .append("ms");

            // 如果有异常，记录异常信息
            if (ex != null) {
                logMsg.append(" | Exception: ")
                        .append(ex.getMessage());
            }

            System.out.println(logMsg.toString());
        }
    }
}
